package com.easy.commons.utils.http.handler;

import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;

/**
 * @author linNaibin
 * @version V1.0
 * @Title: DefaultResulthandler.java
 * @Package com.trs.common.utils.http.handler
 * @Description: TODO
 * @date 2020年8月31日 上午10:25:57
 */
public class DefaultResulthandler implements ResultHandler {

    @Override
    public String handler(CloseableHttpResponse response) {

        System.out.println(" DefaultResulthandler _____ handler ");
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            return "{\"status\":\"error\",\"httpcode\":" + statusLine.getStatusCode() + "}";
        }

        try {


            System.out.println("-----------------------------");
            System.out.println(response.getEntity());
            System.out.println("-----------------------------");

            // 写入文件
            //  FileOutputStream fos = new FileOutputStream("C:\\Users\\linNaibin\\Desktop\\zhihu2.txt");
           /* InputStream ins = response.getEntity().getContent();

            int len = 0;
            byte[] b = new byte[1024];
            while ((len = ins.read(b)) != -1) {
                fos.write(b);

            }
            fos.flush();*/
            //   OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            //  BufferedWriter bw = new BufferedWriter(osw);


            String result = EntityUtils.toString(response.getEntity(), "utf-8");

            //   bw.write(r + "\t\n");

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return "{\"status\":\"error\",\"msg\":" + e.getMessage() + "}";
        }
    }

}
